<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <!-- <el-form-item label="租户编号" prop="tenantId">
              <el-input v-model="queryParams.tenantId" placeholder="请输入租户编号" clearable @keyup.enter="handleQuery" />
            </el-form-item> -->
            <el-form-item label="企业名称" prop="enterpriseName">
              <el-input v-model="queryParams.enterpriseName" placeholder="请输入企业名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="联系人" prop="contactPerson">
              <el-input v-model="queryParams.contactPerson" placeholder="请输入联系人" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="queryParams.phone" placeholder="请输入联系电话" clearable @keyup.enter="handleQuery" />
            </el-form-item>

            <!-- 新增租赁信息查询条件 -->

            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Plus" @click="handleAdd">新增</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="hover">
      <el-table border :data="tenantList" @selection-change="handleSelectionChange" :row-class-name="tableRowClassName">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column v-if="false" label="id" align="center" prop="id" />
        <!-- <el-table-column label="租户编号" align="center" prop="tenantId" width="100" /> -->
        <el-table-column label="企业名称" align="center" prop="enterpriseName" min-width="260" show-overflow-tooltip />
        <!-- <el-table-column label="企业地址" align="center" prop="address" min-width="200" show-overflow-tooltip /> -->
        <el-table-column label="联系人" align="center" prop="contactPerson" width="100" />
        <el-table-column label="联系电话" align="center" prop="phone" width="120" />
        <el-table-column label="企业简介" align="center" prop="enterpriseIntro" min-width="200" show-overflow-tooltip />
        <el-table-column label="备注" align="center" prop="remark" min-width="150" show-overflow-tooltip> </el-table-column>

        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150" fixed="right">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button v-hasPermi="['system:tenant:edit']" link type="primary" @click="handleUpdate(scope.row)">修改</el-button>
            </el-tooltip>

            <el-tooltip content="删除" placement="top" v-if="roleSetting === 'admin'">
              <el-button v-hasPermi="['system:tenant:remove']" link type="primary" @click="handleDelete(scope.row)"> 删除</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改租户对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="800px" append-to-body>
      <el-form ref="tenantFormRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="企业名称" prop="enterpriseName">
              <el-input v-model="form.enterpriseName" placeholder="请输入企业名称" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="联系人" prop="contactPerson">
              <el-input v-model="form.contactPerson" placeholder="请输入联系人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="form.contactPhone" placeholder="请输入联系电话" maxlength="11" />
            </el-form-item>
          </el-col>

          <!-- <el-col :span="12">
            <el-form-item label="企业地址" prop="address">
              <el-input v-model="form.address" placeholder="请输入企业地址" />
            </el-form-item>
          </el-col> -->

          <!-- 新增楼宇楼层房间选择 -->

          <!-- 新增租赁信息字段 -->

          <!-- 新增图片上传 -->
          <el-col :span="12">
            <el-form-item label="企业Logo" prop="logoUrl">
              <el-upload
                class="avatar-uploader"
                :action="uploadUrl"
                :headers="uploadHeaders"
                :show-file-list="false"
                :on-success="handleLogoSuccess"
                :before-upload="beforeLogoUpload"
              >
                <img v-if="form.logoUrl" :src="form.logoUrl" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="企业简介" prop="enterpriseIntro">
              <el-input v-model="form.enterpriseIntro" type="textarea" placeholder="请输入企业简介" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="Tenant">
import { listTenant, removeTenant, addTenant, updateTenant, downloadImage } from '@/api/system/building';
import { selectTenantPackage } from '@/api/system/tenantPackage';
import { TenantVO, TenantForm, TenantQuery } from '@/api/system/tenant/types';
import { TenantPkgVO } from '@/api/system/tenantPackage/types';
import { ref, reactive, toRefs } from 'vue';
import { ComponentInternalInstance, getCurrentInstance } from 'vue';
import { ElForm } from 'element-plus';
import { useUserStore } from '@/store/modules/user';

interface Building {
  id: number;
  name: string;
}

interface Floor {
  id: number;
  name: string;
  buildingId: number;
}

interface Room {
  id: number;
  name: string;
  floorId: number;
}

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_tenant_status } = toRefs(proxy?.useDict('sys_tenant_status'));

const userStore = useUserStore();
const userId = ref(userStore.userId);
const tenantList = ref<any>([]);
const packageList = ref<TenantPkgVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<InstanceType<typeof ElForm>>();
const tenantFormRef = ref<InstanceType<typeof ElForm>>();

// 楼宇楼层房间相关数据
const buildingList = ref<Building[]>([]);
const floorList = ref<Floor[]>([]);
const roomList = ref<Room[]>([]);

const roleSetting = ref(localStorage.getItem('username'));

const dialog = reactive({
  visible: false,
  title: ''
});

const form = ref({
  id: '',
  phone: '',
  logoUrl: '',
  logoId: '',
  enterpriseName: '',
  enterpriseIntro: '',
  address: '',
  contactPerson: '',
  contactPhone: ''
});

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    enterpriseName: '',
    enterpriseIntro: '',
    address: '',
    contactPerson: '',
    contactPhone: ''
  },

  rules: {
    enterpriseName: [{ required: true, message: '企业名称不能为空', trigger: 'blur' }],
    enterpriseIntro: [{ required: true, message: '联系人不能为空', trigger: 'blur' }]
  }
});

const { queryParams, rules } = toRefs(data);

// 文件上传相关
const uploadUrl = '/dev-api/park/housing/uploadImage';
const uploadHeaders = {
  Authorization: 'Bearer ' + userStore.token
};

const handleLogoSuccess = async (response: any) => {
  if (response.code === 200) {
    console.log('response:', response);
    // 加载新上传的图片
    await loadImageForFile(response.data.id);
    form.value.logoId = response.data.id;
    // 显示上传后的图片预览
    // form.value.logoUrl = response.data.url || `/api/file/${response.data.id}`;
    ElMessage.success('上传成功');
  } else {
    ElMessage.error(response.msg || '上传失败');
  }
};

// 为单个文件加载图片
const loadImageForFile = async (logoId: any) => {
  if (logoId) {
    try {
      const response = await downloadImage(logoId);
      console.log('response', response);
      // 验证响应是否为blob格式
      if (response instanceof Blob) {
        // 将blob转换为Data URL
        form.value.logoUrl = URL.createObjectURL(response);
      } else {
        console.error('响应不是blob格式:', response);
        // 备用URL
        // file.imageUrl = `http://localhost:8080/park/housing/downloadImage/${file.filePath}`;
      }
    } catch (error) {
      console.error('获取图片失败:', error);
      // 出错时返回备用URL
      // file.imageUrl = `http://localhost:8080/park/housing/downloadImage/${file.filePath}`;
    }
  }
};

const beforeLogoUpload = (file: File) => {
  const isImage = file.type.startsWith('image/');
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isImage) {
    proxy?.$message.error('只能上传图片文件!');
  }
  if (!isLt2M) {
    proxy?.$message.error('图片大小不能超过 2MB!');
  }
  return isImage && isLt2M;
};

const handleLicenseSuccess = (response: any) => {
  form.value.licenseImageUrl = response.url;
};

const beforeLicenseUpload = (file: File) => {
  const isImage = file.type.startsWith('image/');
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isImage) {
    proxy?.$message.error('只能上传图片文件!');
  }
  if (!isLt2M) {
    proxy?.$message.error('图片大小不能超过 2MB!');
  }
  return isImage && isLt2M;
};

// 计算表格中的租期时长
const calculateTableLeaseDuration = (row: TenantVO) => {
  if (!row.leaseStartTime || !row.leaseEndTime) return '-';

  const start = new Date(row.leaseStartTime);
  const end = new Date(row.leaseEndTime);

  if (isNaN(start.getTime()) || isNaN(end.getTime())) return '-';

  const diffTime = end.getTime() - start.getTime();
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

  if (diffDays < 30) {
    return `${diffDays}天`;
  } else if (diffDays < 365) {
    const months = Math.round(diffDays / 30);
    return `${months}个月`;
  } else {
    const years = Math.round(diffDays / 365);
    return `${years}年`;
  }
};

// 获取位置信息文本
const getLocationText = (row: TenantVO) => {
  const parts = [];
  if (row.region) parts.push(row.region);
  if (row.building) parts.push(row.building);
  if (row.floor) parts.push(row.floor);
  if (row.roomNumber) parts.push(row.roomNumber);
  return parts.join(' - ') || '-';
};

// 加载楼宇列表
const loadBuildingList = () => {
  buildingList.value = [
    { id: 1, name: 'A栋' },
    { id: 2, name: 'B栋' },
    { id: 3, name: 'C栋' }
  ];
};

// 加载楼层列表
const loadFloorList = (buildingId: number) => {
  floorList.value = [
    { id: 1, name: '1楼', buildingId: 1 },
    { id: 2, name: '2楼', buildingId: 1 },
    { id: 3, name: '3楼', buildingId: 1 },
    { id: 4, name: '1楼', buildingId: 2 },
    { id: 5, name: '2楼', buildingId: 2 },
    { id: 6, name: '1楼', buildingId: 3 }
  ].filter((floor) => floor.buildingId === buildingId);
};

// 加载房间列表
const loadRoomList = (floorId: number) => {
  roomList.value = [
    { id: 1, name: '101', floorId: 1 },
    { id: 2, name: '102', floorId: 1 },
    { id: 3, name: '201', floorId: 2 },
    { id: 4, name: '202', floorId: 2 },
    { id: 5, name: '301', floorId: 3 },
    { id: 6, name: '401', floorId: 4 }
  ].filter((room) => room.floorId === floorId);
};

// 楼宇变化处理
const handleBuildingChange = (buildingId: number) => {
  form.value.floorId = undefined;
  form.value.roomId = undefined;
  loadFloorList(buildingId);
};

// 楼层变化处理
const handleFloorChange = (floorId: number) => {
  form.value.roomId = undefined;
  loadRoomList(floorId);
};

// 获取租户套餐列表
// const getTenantPackage = async () => {
//   const res = await selectTenantPackage();
//   packageList.value = res.data;
// };

/** 查询租户列表 */
const getList = async () => {
  loading.value = true;
  const res = await listTenant(queryParams.value);
  tenantList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

// 计算租户到期状态
const calculateExpiryStatus = (tenant: TenantVO) => {
  if (!tenant.expireTime) {
    tenant.daysUntilExpiry = 0;
    tenant.expiryStatus = 'normal';
    return;
  }

  const expireDate = new Date(tenant.expireTime);
  const currentDate = new Date();
  const diffTime = expireDate.getTime() - currentDate.getTime();
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

  tenant.daysUntilExpiry = diffDays;

  if (diffDays < 0) {
    tenant.expiryStatus = 'expired';
  } else if (diffDays <= 30) {
    tenant.expiryStatus = 'expiring_soon';
  } else {
    tenant.expiryStatus = 'normal';
  }
};

// 获取到期标签类型
const getExpiryTagType = (row: TenantVO) => {
  switch (row.expiryStatus) {
    case 'expired':
      return 'danger';
    case 'expiring_soon':
      return 'warning';
    default:
      return 'success';
  }
};

// 租户状态修改
const handleStatusChange = async (row: TenantVO) => {
  // const text = row.status === '0' ? '启用' : '停用';
  // try {
  //   await proxy?.$modal.confirm(`确认要"${text}""${row.companyName}"租户吗？`);
  //   await changeTenantStatus(row.id, row.tenantId, row.status);
  //   proxy?.$modal.msgSuccess(text + '成功');
  // } catch {
  //   row.status = row.status === '0' ? '1' : '0';
  // }
};

// 取消按钮
const cancel = () => {
  reset();
  dialog.visible = false;
};

// 表单重置
const reset = () => {
  form.value = {
    id: '',
    enterpriseName: '',
    enterpriseIntro: '',
    address: '',
    contactPerson: '',
    contactPhone: ''
  };
  tenantFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

// 多选框选中数据
const handleSelectionChange = (selection: TenantVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  // getTenantPackage();
  loadBuildingList();
  dialog.visible = true;
  dialog.title = '添加企业';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: any) => {
  reset();

  form.value = { ...row };
  form.value.contactPhone = form.value.phone;
  console.log('row===', row);
  await loadImageForFile(form.value.logoId);
  dialog.title = '修改企业';
  dialog.visible = true;
  open.value = true;
};

/** 提交按钮 */
const submitForm = () => {
  tenantFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      form.value.phone = form.value.contactPhone;
      buttonLoading.value = true;
      if (form.value.id) {
        await updateTenant(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addTenant(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: TenantVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm(`是否确认删除此企业数据项？`);
  loading.value = true;
  await removeTenant(_ids).finally(() => (loading.value = false));
  await getList();
  proxy?.$modal.msgSuccess('删除成功');
};

/** 同步租户套餐按钮操作 */
const handleSyncTenantPackage = async (row: TenantVO) => {
  // try {
  //   await proxy?.$modal.confirm(`是否确认同步租户套餐租户编号为"${row.tenantId}"的数据项？`);
  //   loading.value = true;
  //   await syncTenantPackage(row.tenantId, row.packageId);
  //   await getList();
  //   proxy?.$modal.msgSuccess('同步成功');
  // } catch {
  //   return;
  // } finally {
  //   loading.value = false;
  // }
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'system/tenant/export',
    {
      ...queryParams.value
    },
    `tenant_${new Date().getTime()}.xlsx`
  );
};

// 表格行样式
const tableRowClassName = ({ row }: { row: TenantVO }) => {
  if (row.expiryStatus === 'expired') {
    return 'expired-row';
  } else if (row.expiryStatus === 'expiring_soon') {
    return 'warning-row';
  }
  return '';
};

getList();
</script>

<style scoped>
.avatar-uploader {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}

:deep(.expired-row) {
  --el-table-tr-bg-color: var(--el-color-danger-light-9);
}

:deep(.warning-row) {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}
</style>
